package net.opentsdb.tsd;

import net.opentsdb.core.TSDB;
import net.opentsdb.core.TSQuery;
import net.opentsdb.core.TSSubQuery;
import net.opentsdb.core.Tags;
import net.opentsdb.query.expression.ExpressionTree;
import net.opentsdb.query.filter.TagVFilter;
import net.opentsdb.stats.QueryStats;
import org.jboss.netty.handler.codec.http.HttpMethod;

import java.util.*;

/**
 * @Author hujf
 * @Date 2022/3/1 10:19
 * @Description 查询
 */
public class QueryRpc  implements HttpRpc{
    @Override
    public void execute(TSDB tsdb, HttpQuery query) {
        final String[] uri = query.explodeAPIPath();
        String endpoint = uri.length>1?uri[1]:"";

        if(endpoint.toLowerCase().equals("last")){

        }
        handleQuery(tsdb,query,false);
    }

    private void handleQuery(TSDB tsdb, HttpQuery query, boolean allow_expressions) {
       // final long start = DateTime.
        TSQuery data_query = null;
        final List<ExpressionTree> expression;
        if(query.method()== HttpMethod.POST){

        }else{
            expression = new ArrayList<ExpressionTree>();
            data_query = praseQuery(tsdb,query,expression);
        }

        data_query.validateAndSetQuery();

        final QueryStats queryStats = new QueryStats(query.getRemoteAddress(),data_query,query.getPrintableHeaders());
        data_query.setQueryStats(queryStats);
        query.setStat(queryStats);

        int nqueries = data_query.getQueries().size();

        data_query.buildQueriedAsync(tsdb);

    }

    private TSQuery praseQuery(TSDB tsdb, HttpQuery query, List<ExpressionTree> expression) {
        TSQuery data_query  = new TSQuery();
        data_query.setStart(query.getQueryStringParam("start"));
        data_query.setEnd(query.getQueryStringParam("end"));
        if(query.hasQueryStringParam("m")){
            final List<String> legacy_queries = query.getQueryStringParams("m");
            for(String q:legacy_queries){
                parseMTypeSubQuery(q,data_query);
            }
        }

        if(expression!=null){

        }
        Set<TSSubQuery> querySet = new LinkedHashSet<>(data_query.getQueries());
        data_query.getQueries().clear();
        data_query.getQueries().addAll(querySet);

        return data_query;
    }

    private static void parseMTypeSubQuery(String q, TSQuery data_query) {
        final String[] parts = Tags.splitString(q,':');
        int i = parts.length;
        if(i<2||i>5){

        }

        final TSSubQuery sub_query = new TSSubQuery();
        sub_query.setAggregator(parts[0]);

        i--;
        List<TagVFilter> filters = new ArrayList<TagVFilter>();

        sub_query.setMetric(Tags.parseWithMetricAndFilters(parts[i],filters));
        sub_query.setFilters(filters);

        if(data_query.getQueries()==null){
            ArrayList<TSSubQuery> subs = new ArrayList<>(1);
            data_query.setQueries(subs);
        }
        data_query.getQueries().add(sub_query);
    }
}
